package com.easymusic;

import easymusic.baseutility.EasyMusicAppService;
import easymusic.baseinterface.IMediaDataService;
import easymusic.baseutility.EasyMusicApplication;

import easymusic.baseinterface.*;
import easymusic.baseinterface.IBasicService.ServiceID;
import easymusic.baseinterface.IMediaService.State;
import android.os.Build;
import android.os.Bundle;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Notification.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

@SuppressLint("NewApi")
public class EasyMusicMainActivity extends Activity 
			implements OnDismissListener, OnItemClickListener, 
			OnSeekBarChangeListener, OnClickListener, IMediaService.ICallback{
	
	public static final String MEDIA_PATH = "MEDIA_PATH";
	public static final String IS_RECURSIVE = "IS_RECURSIVE";
	public static final String SHUFFLE = "SHUFFLE"; 
	public static final int GET_FOLDER_DLG_ID = 0;
	public static final String PLAY_MEDIA_PATH = "PLAY_MEDIA_PATH";
	public static final String STANDARD_TITLE = "EasyMusic";
	
	private EasyMusicSelectDirectory m_dirDlg;
	
	private IMediaService m_playService;
	private String m_strTitle;
	private int m_iDuration;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_easy_music_main);
        
        ListView list = (ListView)findViewById(R.id.media_list);
        list.setOnItemClickListener(this);
        
        SeekBar playProgress = (SeekBar)findViewById(R.id.play_progress);
        playProgress.setOnSeekBarChangeListener(this);
        
        ImageButton stopButton = (ImageButton)findViewById(R.id.image_button_stop);
        stopButton.setOnClickListener(this);
        
        ImageButton pauseButton = (ImageButton)findViewById(R.id.image_button_pause);
        pauseButton.setOnClickListener(this);
     
        /*if (!refreshMedium()){
        	return;
        }
        
        if (!refreshListView()){
        	return;
        }*/
        EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
    	application.setActivity(this);
        m_playService = (IMediaService) application.getService(ServiceID.MediaService);
    	if (null != m_playService){
    		m_playService.registerCallback(this);
    	}
        refreshListView();
        
        m_strTitle = application.getCurrentTitle();
    	m_iDuration = application.getDuration();
    	
		SeekBar progress = (SeekBar)findViewById(R.id.play_progress);
		progress.setMax(application.getDuration() / 1000);
        
        if (!refreshPlayProgress()){
        	return;
        }
    }
    
    @Override
    protected void onDestroy(){
    	super.onDestroy();
    }
    
    @Override
    protected void onResume (){
    	super.onResume(); 
    	
    	
    	
    	
    	
    }
    
    @Override
    protected void onRestart (){
    	super.onRestart();
    }
    
    private boolean refreshPlayProgress(){
    	SeekBar playProgress = (SeekBar)findViewById(R.id.play_progress);
    	playProgress.setProgress(0);
    	
    	return true;
    }
    
    public boolean refreshMedium(){
    	/*SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
    	String strMediaPath = settings.getString(MEDIA_PATH, null);
    	if (null == strMediaPath){
    		return true;
    	}
    	
    	boolean bIsRecursive = settings.getBoolean(IS_RECURSIVE, false);
    	EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
    	application.clearAllMedium();
    	application.searchMedium(strMediaPath, bIsRecursive);*/
    	if (null == m_playService) {
    		return false;
    	}
    	IMediaDataService mediaData = (IMediaDataService)m_playService.getService(IBasicService.ServiceID.MediaDataService);
    	mediaData.refreshMedia();
    	return true;
    	
    }
    
    public boolean refreshListView(){
    	if (null == m_playService){
    		return false;
    	}
    	IMediaDataService mediaData = (IMediaDataService)m_playService.getService(IBasicService.ServiceID.MediaDataService);
    	if (null == mediaData){
    		return false;
    	}
    	
    	int curPos = mediaData.getCurPos();
    	
    	LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	
    	ListView list = (ListView)findViewById(R.id.media_list);
    	MediaViewsAdapter adapter = new MediaViewsAdapter();
    	
    	//EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
    	for (mediaData.moveToFirst(); !mediaData.isEnd(); mediaData.moveToNext()){
    		IMediaDataService.IMediaData data = mediaData.getMediaData();
    		
        	View mediaView = (View)inflater.inflate(R.layout.each_media_view, null);
        	
        	ImageView image = (ImageView)mediaView.findViewById(R.id.media_image);
        	image.setImageBitmap(data.getAlbum());
        	
        	TextView mediaName = (TextView)mediaView.findViewById(R.id.media_name);
        	mediaName.setText(data.getMediaName());
        	
        	adapter.add(mediaView);
    	}
    	
    	list.setAdapter(adapter);
    	
    	mediaData.moveToPosition(curPos);

    	return true;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.easy_music_main, menu);
        
        SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
        /*MenuItem item = menu.add("Sub directories");
        item.setCheckable(true).setChecked(settings.getBoolean(IS_RECURSIVE, false));
        item.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				if (arg0.isChecked()){
					arg0.setChecked(false);
				}else{
					arg0.setChecked(true);
				}
				SharedPreferences settings = getPreferences(Context.MODE_WORLD_WRITEABLE);
				Editor editor = settings.edit();
				editor.putBoolean(IS_RECURSIVE, arg0.isChecked());
				editor.commit();
				return true;
			}
        });*/
        
        MenuItem item = menu.add("Shuffle");
        item.setCheckable(true).setChecked(settings.getBoolean(SHUFFLE, false));
        item.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				if (arg0.isChecked()){
					arg0.setChecked(false);
				}else{
					arg0.setChecked(true);
				}
				SharedPreferences settings = getPreferences(Context.MODE_WORLD_WRITEABLE);
				Editor editor = settings.edit();
				editor.putBoolean(SHUFFLE, arg0.isChecked());
				editor.commit();
				return true;
			}
        	
        });
        
        //item = menu.add("Get medium...");
        /*item.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				showDialog(GET_FOLDER_DLG_ID);  
				return true;
			}
        });*/
        
        item = menu.add(getText(R.string.exit));
        item.setOnMenuItemClickListener(new OnMenuItemClickListener(){
			@Override
			public boolean onMenuItemClick(MenuItem arg0) {
				EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
		    	application.shutDown();
				return true;
			}
        });
        
        
        return true;
    }
    
    @Override  
    protected Dialog onCreateDialog(int id){
    	if (GET_FOLDER_DLG_ID == id){
    		SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
        	String strMediaPath = settings.getString(MEDIA_PATH, "/");
        	m_dirDlg = new EasyMusicSelectDirectory(this, strMediaPath);
        	Dialog dlg =  m_dirDlg.showDialog();
        	dlg.setOnDismissListener(this);
        	
    		return dlg;
    	}
    	
    	return null;    	
    }

	@Override
	public void onDismiss(DialogInterface arg0) {
		SharedPreferences settings = getPreferences(Context.MODE_WORLD_WRITEABLE); 
		Editor editor = settings.edit();
		editor.putString(MEDIA_PATH, m_dirDlg.getCurrentPath());
		editor.commit();
		
		if (!refreshMedium()){
			return;
		}
		
		if (!refreshListView()){
			return;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapter, View view, int position, long arg3) {
		ImageButton pauseButton = (ImageButton)findViewById(R.id.image_button_pause);
		pauseButton.setImageResource(R.drawable.pause);
		
		EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
		application.setCurrentMediaIndex(position);
		m_playService = (IMediaService) application.getService(ServiceID.MediaService);
		IMediaDataService dataService = (IMediaDataService)m_playService.getService(ServiceID.MediaDataService);
		dataService.moveToPosition(position);
		playSong(dataService.getPath());
	}
	
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
		if (!fromUser){
			return;
		}
		
		if (!m_playService.isPlaying()){
			seekBar.setProgress(0);
			return;
		}
		updateTitle(progress * 1000);
	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		m_playService.seek(seekBar.getProgress() * 1000);
	}
	
	public void setUIToStop(){
		ImageButton pauseButton = (ImageButton)findViewById(R.id.image_button_pause);
		pauseButton.setImageResource(R.drawable.play);
		
		TextView text = (TextView)findViewById(R.id.play_name);
		text.setText(STANDARD_TITLE);

		SeekBar playProgress = (SeekBar)findViewById(R.id.play_progress);
		playProgress.setProgress(0);
		
		//updateNotification(getText(R.string.app_name).toString(), getText(R.string.app_name).toString());
	}
	
	private void stop(){
		if (null != m_playService){
			m_playService.stop();
			m_playService = null;
		}
		
	}
	
	private void pause(){
		EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
		m_playService = (IMediaService)application.getService(ServiceID.MediaService);
		State state = m_playService.getState();
		if (state == State.pause || state == State.playing){
			m_playService.pause();
		}else{
			IMediaDataService dataService = (IMediaDataService)m_playService.getService(ServiceID.MediaDataService);
			dataService.moveToFirst();
			playSong(dataService.getPath());
		}
	}

	@Override
	public void onClick(View button) {
		if (button.getId() == R.id.image_button_stop){
			stop();
		}else if (button.getId() == R.id.image_button_pause){
			pause();
		}
	}

	private void playNextSong() {
		EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
		
		SharedPreferences settings = getPreferences(Context.MODE_PRIVATE);
		boolean bContinuePlay = settings.getBoolean(SHUFFLE, false);
		if (!bContinuePlay){
			return;
		}
		
		//String strPath = application.getNextMediaPath();
		//if (null == strPath){
		//	return;
		//}
		
		IMediaDataService dataService = (IMediaDataService)application.getService(ServiceID.MediaDataService);
		if (dataService.isEnd()) {
			return;
		}
		dataService.moveToNext();

		
		playSong(dataService.getPath());
	}
	
	private void playSong(String strPath){
		if (null == strPath){
			return;
		}
		if (null == m_playService){
			return;
		}
		
		m_playService.load(strPath);
		m_strTitle = strPath.substring(strPath.lastIndexOf('/') + 1, strPath.lastIndexOf('.'));
		m_iDuration = m_playService.getDuration();
		
		EasyMusicApplication application = (EasyMusicApplication)getApplicationContext();
		application.setCurrentTitle(m_strTitle);
    	application.setDuration(m_iDuration);
		
		SeekBar progress = (SeekBar)findViewById(R.id.play_progress);
		progress.setMax(m_iDuration / 1000);
		
		m_playService.play();
	}
	
	private String calculateTimeLeft(int currentPosition){
		int timeLeft = m_iDuration - currentPosition;
		int iTime = timeLeft / 1000;
		int iMinutes = iTime / 60;
		int iSeconds = iTime % 60;
		StringBuffer buffer = new StringBuffer();
		buffer.append(iMinutes);
		buffer.append(":");
		buffer.append(iSeconds);
		
		return buffer.toString();
	}
	
	private void updateTitle(int currentPosition){
		String strTimeLeft = calculateTimeLeft(currentPosition);
		TextView text = (TextView)findViewById(R.id.play_name);
		text.setText(strTimeLeft + " " + m_strTitle);
		
		updateNotification(strTimeLeft, m_strTitle);
	}
	
	private void updateNotification(String strTimeLeft, String strTitle){
		Builder builder = new Notification.Builder(getApplicationContext());
    	builder.setSmallIcon(R.drawable.easy_music_icon);
		builder.setContentTitle(strTitle);
		builder.setContentText(getText(R.string.app_name));
		
		Intent intent = new Intent(getApplicationContext(), EasyMusicMainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
    	builder.setContentIntent(pendingIntent);
		
		Notification note = builder.getNotification();
		NotificationManager manager = (NotificationManager)getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
		manager.notify(EasyMusicAppService.FOREGROUD_NOTIFICATION_ID, note);
	}

	@Override
	public void updateState(int currentPosition, State eState) {
		if (State.stop == eState){
			setUIToStop();
			playNextSong();
			return;
		}
		updateTitle(currentPosition);
		
		ImageButton pauseButton = (ImageButton)findViewById(R.id.image_button_pause);
		if (eState == State.playing){
			pauseButton.setImageResource(R.drawable.pause);
		}else{
			pauseButton.setImageResource(R.drawable.play);
		}
		
		SeekBar playProgress = (SeekBar)findViewById(R.id.play_progress);
		playProgress.setProgress(currentPosition / 1000);	
		

	}

	public void setPlayService(IBasicService service) {
        m_playService = (IMediaService)service;
        m_playService.registerCallback(this);
	}
}








































